#!/bin/bash

KUBERNETES_VERSION=v1.13.0

set -e

if ! [ -f coreos.ps1 ];then echo "please exec this shell scipt in coreos folder"; exit ; fi

print_help_info(){
    echo "
CoreOS CLI $KUBERNETES_VERSION

Usages:

init              Download CoreOS ISO files
server            Up CoreOS install local server
cert              Generate Self-Signed Certificates

add-node          Create node ignition yaml file [example: add-node N ]

new-vm            Create new VirtualBox vm [example: new-vm N ]

cleanup           Cleanup Cache

Addons:

coredns           Create coredns addons
dashboard         Create dashboard addons [ token list ]
efk               Create EFK addons [ list ]
heapster          Create heapster addons [ list ]
ingress-nginx     Create Ingress NGINX
metrics-server    Create Metrics-server
"
}

if ! [ -f .env ];then
  cp .env.example .env
fi

# write ssh pub

ssh_pub=$( cat ~/.ssh/id_rsa.pub | cut -d " " -f 2 )

sed -i "s!^SSH_PUB=.*!SSH_PUB=$ssh_pub!g" .env

# cp kube config

if ! [ -d $HOME/.kube ];then mkdir -p $HOME/.kube ; fi

# cp cert/kubectl.kubeconfig ~/.kube/config

_init(){

# Download coreos iso files
cd current

items="coreos_production_iso_image.iso \
        coreos_production_image.bin.bz2 \
        coreos_production_image.bin.bz2.sig \
        version.txt"

for item in $items;do

if ! [ -f $item ];then
  curl -O http://alpha.release.core-os.net/amd64-usr/current/$item
fi

done

cd ..

}

if [ "$1" = 'init' ];then _init ; exit; fi

_efk(){
  if [ "$1" = 'list' ];then
    kubectl get pods -n kube-system -o wide|grep -E 'elasticsearch|fluentd|kibana'
    exit

  fi

  cd ../addons/efk

  kubectl apply -f .
}

_heapster(){
  if [ "$1" = 'list' ];then
    kubectl get pods -n kube-system | grep -E 'heapster|monitoring'
    exit

  fi

  cd ../addons/heapster

  kubectl apply -f .
}

_dashboard(){
  if [ "$1" = 'token' ];then
  set +e

  sudo rm -rf $HOME/.kube/dashboard.kubeconfig

  kubectl create sa dashboard-admin -n kube-system

  kubectl create clusterrolebinding dashboard-admin --clusterrole=cluster-admin --serviceaccount=kube-system:dashboard-admin

  ADMIN_SECRET=$(kubectl get secrets -n kube-system | grep dashboard-admin | awk '{print $1}')

  DASHBOARD_LOGIN_TOKEN=$(kubectl describe secret -n kube-system ${ADMIN_SECRET} | grep -E '^token' | awk '{print $2}')

  echo ${DASHBOARD_LOGIN_TOKEN}

  kubectl config set-cluster kubernetes \
    --certificate-authority=cert/ca.pem \
    --embed-certs=true \
    --server=${KUBE_APISERVER:-https://192.168.57.110:6443} \
    --kubeconfig=$HOME/.kube/dashboard.kubeconfig

  # 设置客户端认证参数，使用上面创建的 Token
  kubectl config set-credentials dashboard_user \
    --token=${DASHBOARD_LOGIN_TOKEN} \
    --kubeconfig=$HOME/.kube/dashboard.kubeconfig

  # 设置上下文参数
  kubectl config set-context default \
    --cluster=kubernetes \
    --user=dashboard_user \
    --kubeconfig=$HOME/.kube/dashboard.kubeconfig

  # 设置默认上下文
  kubectl config use-context default --kubeconfig=$HOME/.kube/dashboard.kubeconfig
  exit
  fi

  if [ "$1" = 'list' ];then
      kubectl get deployment kubernetes-dashboard  -n kube-system
      kubectl --namespace kube-system get pods -o wide
      kubectl get services kubernetes-dashboard -n kube-system
      exit
  fi

  kubectl apply -f ../addons/dashboard.yaml

}

case "$1" in

  server )
  if ! [ -f cert/server-cert.pem ];then
    cd ..
    docker-compose up cfssl
    cd -
  fi

  cd ..
  docker-compose up server

  ;;

  cert )
    cd ..
    docker-compose up cfssl

  ;;

  add-node )
    if [ -z "$2" ];then echo "===> Please Input >3 number"; exit 1; fi

    if [ "$2" -le 3 ];then
      echo "===> Please Input >3 number"
      exit 1
    fi

    cp disk/example/ignition-n.template.yaml disk/ignition-$2.yaml
    sed -i "s#{{n}}#$2#g" disk/ignition-$2.yaml
  ;;

  new-vm )
      if [ -z $2 ];then

        echo -e "===> Please input node num\n\n$ ./coreos create-node N" ; exit

      fi

      # $ VBoxManage list ostypes

      VBoxManage createvm --name "coreos"$2 --ostype 'Linux26_64' --register

      VBoxManage modifyvm "coreos"$2 --memory 2048 --acpi on --boot1 dvd --nic1 hostonly --nic2 bridged

      VBoxManage createmedium --filename "$HOME/VirtualBox VMs/coreos$2/coreos$2.vdi" --size 10000

      VBoxManage storagectl "coreos"$2 --name "IDE Controller" --add ide --controller PIIX4

      VBoxManage storageattach "coreos"$2 --storagectl "IDE Controller" \
          --port 0 --device 0 --type hdd --medium "$HOME/VirtualBox VMs/coreos$2/coreos$2.vdi"

      VBoxManage storageattach "coreos"$2 --storagectl "IDE Controller" \
          --port 0 --device 1 --type dvddrive --medium current/coreos_production_iso_image.iso

      echo "===> Please checkout coreos$2 config, then start it"
  ;;

  cleanup )
    docker image rm ccr.ccs.tencentyun.com/khs1994/kubernetes:${KUBERNETES_VERSION}
  ;;

  dashboard )
   shift
   set +e
   _dashboard $@
  ;;

  efk )
    shift
    set +e
    _efk $@
  ;;

  heapster )
   shift
   set +e
   _heapster $@
  ;;

  ingress-nginx )

    cd ../addons/ingress-nginx

    kubectl apply -f ingress-nginx.yaml
    kubectl apply -f service-nodeport.yaml

  ;;

  coredns )
    kubectl create -f ../addons/coredns.yaml

  ;;

  * )
    print_help_info

  ;;

esac
